package com.team5101.hander;


import com.alibaba.fastjson.JSONObject;
import com.team5101.model.RpcRequest;
import com.team5101.model.RpcResponse;
import com.team5101.util.SpringBeanUtil;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;
import java.util.Objects;

@Slf4j
@Component
public class DemoServiceHandler extends ChannelInboundHandlerAdapter {

    private final SpringBeanUtil springBean;

    public DemoServiceHandler(SpringBeanUtil springBean) {
            this.springBean = springBean;
        }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object data) throws Exception {

        RpcResponse response = new RpcResponse();
        String requestId = null;
        Object result = null;
        Object errorMsg = null;

        log.info("接受到参数：{} ", data);


        //msg：RpcRequest.class
        //判断数据是否调用的方法
        if (Objects.isNull(data)) {
            errorMsg = "请求参数为空";
            return;
        }

        // data ==> RpcRequest
        if (data instanceof RpcRequest) {
            RpcRequest request = (RpcRequest) data;

            String reqId = request.getRequestId();
            if (StringUtils.isBlank(reqId)) {
                errorMsg = "请求Id为空";
                return;
            }
            requestId = reqId;

            //调用的那个服务类
            String className = request.getClassName();
            if (StringUtils.isBlank(className)) {
                errorMsg = "服务类名为空";
                return;
            }
            //调用服务类中的那个方法
            String methodName = request.getMethodName();
            if (StringUtils.isBlank(className)) {
                errorMsg = "方法名为空";
                return;
            }

            Class<?> aClass = Class.forName(className);
            Object beanByType = springBean.getBeanByType(aClass);
            if (null == beanByType) {
                errorMsg = "服务类对象不存在，请检查...";
                return;
            }

            //找到对应的方法
            Method method = aClass.getMethod(methodName, request.getParameterTypes());
            if (null == method) {
                errorMsg = "方法不存在，请检查...";
                return;
            }

            try {
                result = method.invoke(beanByType, request.getParameters());
            } catch (Exception e) {
                errorMsg = e.getMessage();
                log.info("调用目标方法，异常...");
            }
        }

        boolean isSuccess = true;
        if (Objects.nonNull(errorMsg)) {
            isSuccess = false;
            response.setErrorMsg(errorMsg);
        }
        response.setRequestId(requestId);
        response.setIsSuccess(isSuccess);
        response.setResult(result);

        //响应客户端
        ctx.writeAndFlush(JSONObject.toJSONString(response));

    }

}
